package com.yyk.yiliao.ui.login.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.bean.WeixinLogin_Info;
import com.yyk.yiliao.cache.UserCacheManager;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.OkHttp3Utlis;
import com.yyk.yiliao.util.rx.ApiService;


import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WxLogIn_Activity extends BaseActivity {

    @BindView(R.id.mWxLogin_telphone)
    EditText mWxLoginTelphone;
    @BindView(R.id.mWxLogin_edit)
    TextView mWxLoginEdit;
    @BindView(R.id.mWxLogin_cade)
    EditText mWxLoginCade;
    @BindView(R.id.mWxLogin_log)
    Button mWxLoginLog;

    private String openid;
    private String iconurl;
    private String uid;
    private String unionid;
    /**
     * 微信登录相关
     */
    private IWXAPI api;


    private void initIntent() {
        Bundle bundle = getBundle();
        if (bundle != null) {
            openid = bundle.getString("oppenid");
            iconurl = bundle.getString("pic");
            uid = bundle.getString("uid");
            unionid = bundle.getString("unionid");
        }

    }


    @OnClick({R.id.mWxLogin_edit, R.id.mWxLogin_log})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mWxLogin_edit:
                String telphone = mWxLoginTelphone.getText().toString().trim();

                if (telphone.length() != 11) {
                    ToastUtil.showShort(WxLogIn_Activity.this, "请正确输入手机号");
                    return;
                } else if (telphone.length() == 11) {
                    Map<String, String> map = new TreeMap<>();
                    map.put("telphone", telphone);
                    map.put("sign", Md5Util2.createSign(map));
                    OkHttp3Utlis.getIntance().postOkhttp(ApiService.BASE_URL + "/mobile/Alidayu/sendSMS", map, new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String result = response.body().string().trim();
                            Logger.e("验证码" + result);
                        }
                    });
                    TimeCount timeCount = new TimeCount(60000, 1000);
                    timeCount.start();
                }
                break;
            case R.id.mWxLogin_log:
                String telphone2 = mWxLoginTelphone.getText().toString().trim();
                String code = mWxLoginCade.getText().toString().trim();
                //                int codeInt = Integer.valueOf(code);
                Map<String, String> map2 = new TreeMap<>();
                map2.put("telphone", telphone2);
                map2.put("code", code);
                map2.put("openid", openid + "");
                map2.put("uid", uid + "");
                map2.put("pic", iconurl);
                map2.put("unionid", unionid);
                map2.put("sign", Md5Util2.createSign(map2));

                OkHttp3Utlis.getIntance().postOkhttp(ApiService.BASE_URL + "/mobile/Common/Authorizationbinding", map2, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        Logger.e("微信绑定" + result);
                        Gson gson = new Gson();
                        WeixinLogin_Info info = gson.fromJson(result, WeixinLogin_Info.class);
                        if (info.getCode() == 1) {
                            WeixinLogin_Info.DataBean data = info.getData();
                            Hawk.put("real", data.getReal());//身份认证
                            Hawk.put("statusfo", data.getBank_type()); //鲁亿通
                            Hawk.put("real_name", data.getReal_name());//姓名
                            Hawk.put("phone", data.getPatient_phone());//手机号
                            Hawk.put("uid", info.getData().getUid()); //跳转后获得
                            if (!TextUtils.isEmpty(iconurl)) {
                                Hawk.put("wxpic", iconurl);//微信登陆的时候有照片
                            }
                            // todo zk  登录成功，将用户的环信ID、昵称和头像缓存在本地
                            String userId = info.getData().getChat_id();
                            String nickName = info.getData().getReal_name();
                            String avatarUrl = info.getData().getIconurl();
                            UserCacheManager.save(userId, nickName + "", avatarUrl);
                            Logger.e("登录前的" + userId + "_" + avatarUrl + "_" + nickName);

                            //登录
                            EMClient.getInstance().login(info.getData().getChat_id() + "", "ca9b09d8d1f9", new EMCallBack() {//回调
                                @Override
                                public void onSuccess() {
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            // ** manually load all local groups and conversation
                                            EMClient.getInstance().groupManager().loadAllGroups();
                                            EMClient.getInstance().chatManager().loadAllConversations();
                                            //    Log.d("main", "登录聊天服务器成功！");
                                            ToastUtil.showShort(mActivity, "登录成功");

                                        }
                                    });
                                }

                                @Override
                                public void onProgress(int progress, String status) {

                                }

                                @Override
                                public void onError(int code, String message) {
                                    if (code == -1005) {
                                        message = "用户名或密码错误";
                                    }
                                    final String msg = message;
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            Log.d("main", "登陆聊天服务器失败！");
//                                            ToastUtil.showShort(mActivity, "登陆聊天服务器失败");

                                        }
                                    });
                                }
                            });
                            finish();
//                            startAct(Main_Activity.class, true);
                        } else {
                            ToastUtil.showShort(mActivity, "请重新正确输入");
                        }

                    }
                });

                break;
        }
    }

    /**
     * 设置 60秒时间 倒计时
     */
    private class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mWxLoginEdit.setBackgroundColor(getResources().getColor(R.color.gray_c1));
            mWxLoginEdit.setClickable(false);
            mWxLoginEdit.setText("(" + millisUntilFinished / 1000 + ") 秒重新发送");
        }

        @Override
        public void onFinish() {
            mWxLoginEdit.setText("重新获取验证码");
            mWxLoginEdit.setClickable(true);
            mWxLoginEdit.setBackgroundColor(getResources().getColor(R.color.gray_c1));

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        EventBus.getDefault().unregister(this);
//        finish();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_wx_log_in;
    }

    @Override
    public void initView() {
        initToolbar();
        initEdittext();


    }

    private void initEdittext() {
        mWxLoginTelphone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 11) {
                    mWxLoginEdit.setTextColor(getResources().getColor(R.color.blue_51));
                }
            }
        });


    }

    private void initToolbar() {
        setBackArrow();
        setTitle("绑定手机号码");
    }

    @Override
    public void initData() {
//        EventBus.getDefault().register(this);
        initIntent();
    }


}
